import 'package:dio/dio.dart';
import 'package:read_flutter/common/Tools.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:read_flutter/common/BookUtils.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ReadApiModels extends Model {
  List<BookInfo> _books = [];

  get books => _books;

  Future updateBooks() async {
    _books = await BookInfoProvider().getBookShelf();
    notifyListeners();
  }

  Future checkUpdateBooks() async {
    for (BookInfo book in _books) {
      Response res = await Tools().request('/search/getcataloglist',
          {'link': book.cataloglink, 'source': book.source});
      if (res.data["code"] == "0") {
        List<dynamic> catalogList = [];
        catalogList = res.data["result"];
        await BookTools().updateBookContentList(book, catalogList);
      }else{
        Tools().showToast("获取书籍更新失败");
      }
    }
    updateBooks();
  }

  Future setupModels() async {
    checkUpdateBooks();
    checkUserSettings();
  }

  checkUserSettings() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _fontSize = prefs.getDouble('FONTSIZE') ?? 20;
    _textColor = prefs.getInt("TEXTCOLOR") ?? 0xff000000;
    _backgroundColor = prefs.getInt('BACKGROUNDCOLOR') ?? 0xffF0E68C;
    _night = prefs.getBool("NIGHT") ?? false;
  }

  double _fontSize;

  get fontSize => _fontSize;

  updateFontSize(double fs) async {
    _fontSize = fs;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setDouble("FONTSIZE", fs);
    notifyListeners();
  }

  int _backgroundColor;

  get backgroundColor => _backgroundColor;

  updateBackgroundColor(int bgc) async {
    _backgroundColor = bgc;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt("BACKGROUNDCOLOR", bgc);
    notifyListeners();
  }

  int _textColor;

  get textColor => _textColor;

  updateTextColor(int tc) async {
    _textColor = tc;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt("TEXTCOLOR", tc);
    notifyListeners();
  }

  bool _night = false;

  get night => _night;

  updateNight(bool n) async {
    _night = n;
    if(n){
      updateBackgroundColor(0xff111111);
      updateTextColor(0xff808080);
    }else{
      updateBackgroundColor(0xffF0E68C);
      updateTextColor(0xff000000);
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool("NIGHT", n);
    notifyListeners();
  }






//
//  ReadApiModels of(context) =>
//      ScopedModel.of<ReadApiModels>(context);

}
